<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言Node.js是基于事件驱动的；当我们的服务器监听请求时，请求其实任意时刻都可以到达。对于多线程的语言，任何时候当有请求进入的时候，服务器就为这一请求新建一个进程。这就是是多线程的使用。 但Node.js为单线程，因此不能这样处理，这里我们定义一个处理请求的函数，就是回调函数，只有在接收请求时才会调用这个回调，这就是Node的异步。 在Node中,我们定义回调函数被触发时，有两个参数被传入：r">
<meta property="og:type" content="article">
<meta property="og:title" content="nodejs模块">
<meta property="og:url" content="http://example.com/2021/10/14/node/node.js%E6%A8%A1%E5%9D%97/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言Node.js是基于事件驱动的；当我们的服务器监听请求时，请求其实任意时刻都可以到达。对于多线程的语言，任何时候当有请求进入的时候，服务器就为这一请求新建一个进程。这就是是多线程的使用。 但Node.js为单线程，因此不能这样处理，这里我们定义一个处理请求的函数，就是回调函数，只有在接收请求时才会调用这个回调，这就是Node的异步。 在Node中,我们定义回调函数被触发时，有两个参数被传入：r">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-10-14T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-03T08:20:25.451Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="node狼书">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/10/14/node/node.js%E6%A8%A1%E5%9D%97/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>nodejs模块 | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/10/14/node/node.js%E6%A8%A1%E5%9D%97/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          nodejs模块
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-10-14 12:18:39" itemprop="dateCreated datePublished" datetime="2021-10-14T12:18:39+08:00">2021-10-14</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:20:25" itemprop="dateModified" datetime="2021-11-03T16:20:25+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>Node.js是基于事件驱动的；当我们的服务器监听请求时，请求其实任意时刻都可以到达。对于多线程的语言，任何时候当有请求进入的时候，服务器就为这一请求新建一个进程。这就是是多线程的使用。</p>
<p>但Node.js为单线程，因此不能这样处理，这里我们定义一个处理请求的函数，就是回调函数，只有在接收请求时才会调用这个回调，这就是Node的异步。</p>
<p>在Node中,我们定义回调函数被触发时，有两个参数被传入：request和response。我们可以通过它来处理HTTP请求的细节，并且响应请求。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">onRequest</span>(<span class="params">request, response</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Request received."</span>);</span><br><span class="line">  response.writeHead(<span class="number">200</span>, &#123;<span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span>&#125;);</span><br><span class="line">  response.write(<span class="string">"Hello World"</span>);</span><br><span class="line">  response.end();</span><br><span class="line">&#125;</span><br><span class="line">http.createServer(onRequest).listen(<span class="number">8888</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"Server has started."</span>);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">当收到请求时，使用 response.writeHead() 函数发送一个HTTP状态200和HTTP头的内容类型（content-type），使用 response.write() 函数在HTTP相应主体中发送文本“Hello World"。</span></span><br><span class="line"><span class="comment">最后，我们调用 response.end() 完成响应。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在C++或C#中，当我们谈到对象，指的是类或者结构体的实例。对象根据他们实例化的模板（就是所谓的类），会拥有不同的属性和方法。但在JavaScript里对象不是这个概念。在JavaScript中，对象就是一个键/值对的集合 – 你可以把JavaScript的对象想象成一个键为字符串类型的字典。但如果JavaScript的对象仅仅是键/值对的集合，它又怎么会拥有方法呢？好吧，这里的值可以是字符串、数字或者……函数！</p>
<p><strong>在node中除了代码，所有的一切都是并行执行的。</strong>Node.js可以在不新增额外线程的情况下，依然可以对任务进行并行处理。它通过事件event loop机制来实现并行操作，同时，使用回调。</p>
<h1 id="简单实践"><a href="#简单实践" class="headerlink" title="简单实践"></a>简单实践</h1><p>正常情况下，应用已经可以通过应用各层之间传递值的方式（请求处理程序 -&gt; 请求路由 -&gt; 服务器）将请求处理程序返回的内容（请求处理程序最终要显示给用户的内容）传递给HTTP服务器。</p>
<p>现在我们采用如下这种新的实现方式：相对采用将内容传递给服务器的方式，我们这次采用将服务器“传递”给内容的方式。 从实践角度来说，就是将<em>response</em>对象（从服务器的回调函数*onRequest()*获取）通过请求路由传递给请求处理程序。 随后，处理程序就可以采用该对象上的函数来对请求作出响应。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//server.js</span></span><br><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"><span class="keyword">var</span> url = <span class="built_in">require</span>(<span class="string">"url"</span>);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">start</span>(<span class="params">route, handle</span>) </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">onRequest</span>(<span class="params">request, response</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> pathname = url.parse(request.url).pathname;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Request for "</span> + pathname + <span class="string">" received."</span>);</span><br><span class="line"></span><br><span class="line">    route(handle, pathname, response);</span><br><span class="line">  &#125;</span><br><span class="line">  http.createServer(onRequest).listen(<span class="number">8888</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Server has started."</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">exports.start = start;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">相对此前从route()函数获取返回值的做法，这次我们将response对象作为第三个参数传递给route()函数，并且，我们将onRequest()处理程序中所有有关response的函数调都移除，因为我们希望这部分工作让route()函数来完成。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">下面就来看看我们的router.js:</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">route</span>(<span class="params">handle, pathname, response</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"About to route a request for "</span> + pathname);</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> handle[pathname] === <span class="string">'function'</span>) &#123;</span><br><span class="line">    handle[pathname](response);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"No request handler found for "</span> + pathname);</span><br><span class="line">    response.writeHead(<span class="number">404</span>, &#123;<span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span>&#125;);</span><br><span class="line">    response.write(<span class="string">"404 Not found"</span>);</span><br><span class="line">    response.end();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">exports.route = route;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">同样的模式：相对此前从请求处理程序中获取返回值，这次取而代之的是直接传递response对象。</span></span><br><span class="line"><span class="comment">如果没有对应的请求处理器处理，我们就直接返回“404”错误。</span></span><br><span class="line"><span class="comment">最后，我们将requestHandler.js修改为如下形式</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">var</span> exec = <span class="built_in">require</span>(<span class="string">"child_process"</span>).exec;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">start</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Request handler 'start' was called."</span>);</span><br><span class="line"></span><br><span class="line">  exec(<span class="string">"ls -lah"</span>, <span class="function"><span class="keyword">function</span> (<span class="params">error, stdout, stderr</span>) </span>&#123;</span><br><span class="line">    response.writeHead(<span class="number">200</span>, &#123;<span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span>&#125;);</span><br><span class="line">    response.write(stdout);</span><br><span class="line">    response.end();</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">upload</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Request handler 'upload' was called."</span>);</span><br><span class="line">  response.writeHead(<span class="number">200</span>, &#123;<span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span>&#125;);</span><br><span class="line">  response.write(<span class="string">"Hello Upload"</span>);</span><br><span class="line">  response.end();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">exports.start = start;</span><br><span class="line">exports.upload = upload;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">我们的处理程序函数需要接收response参数，为了对请求作出直接的响应。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">start处理程序在exec()的匿名回调函数中做请求响应的操作，而upload处理程序仍然是简单的回复“Hello World”，只是这次是使用response对象而已。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">这时再次我们启动应用（node index.js），一切都会工作的很好。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">如果想要证明/start处理程序中耗时的操作不会阻塞对/upload请求作出立即响应的话，可以将requestHandlers.js修改为如下形式：</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">var</span> exec = <span class="built_in">require</span>(<span class="string">"child_process"</span>).exec;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">start</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Request handler 'start' was called."</span>);</span><br><span class="line"></span><br><span class="line">  exec(<span class="string">"find /"</span>,</span><br><span class="line">    &#123; <span class="attr">timeout</span>: <span class="number">10000</span>, <span class="attr">maxBuffer</span>: <span class="number">20000</span>*<span class="number">1024</span> &#125;,</span><br><span class="line">    <span class="function"><span class="keyword">function</span> (<span class="params">error, stdout, stderr</span>) </span>&#123;</span><br><span class="line">      response.writeHead(<span class="number">200</span>, &#123;<span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span>&#125;);</span><br><span class="line">      response.write(stdout);</span><br><span class="line">      response.end();</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">upload</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Request handler 'upload' was called."</span>);</span><br><span class="line">  response.writeHead(<span class="number">200</span>, &#123;<span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span>&#125;);</span><br><span class="line">  response.write(<span class="string">"Hello Upload"</span>);</span><br><span class="line">  response.end();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">exports.start = start;</span><br><span class="line">exports.upload = upload;</span><br></pre></td></tr></table></figure>

<h1 id="模块规范"><a href="#模块规范" class="headerlink" title="模块规范"></a>模块规范</h1><h2 id="CommonJS规范"><a href="#CommonJS规范" class="headerlink" title="CommonJS规范"></a>CommonJS规范</h2><p>CommonJS是一个规范，通过简单的API声明服务器的模块，目标是让JS可以运行在浏览器意外的所有地方，</p>
<p>Modules/1.0规范：</p>
<p>1、定义全局函数require，通过传入模块标识来引入其他模块，执行的结果即其他模块暴露出的API；2、如果被require函数引入的模块也包含依赖，则依次加载这些依赖；3、如果引入模块失败，则require函数应该抛出异常；4、模块通过变量exports来向外暴露API，exports只能是一个对象，暴露的API须作为此对象的属性。</p>
<p>之前的规范主要源于服务端，为浏览器端同样实现模块化，需对规范进行升级，基本分为两个派别：</p>
<p>1、Webpack等使用的Browserify工具。</p>
<p>2、async派：不属于CommonJS的范畴，独立制定浏览器端的JS模块化规范AMD。代表项目有RequireJS和SeaJS。</p>
<p>Node.js与CommonJS在模块系统主要通过两个关键字进行交互，即require、exports。在Node.js的实现中，模块的名字在node_modules目录下，如果不在，就会去查找指定路径。而exports是一个特殊的对象，其任何输出都会作为一个对外暴露的公共API。</p>
<p>Node.js与CommonJS的区别：在Node.js中。module.exports是真正特殊对象，真正的对外暴露接口，而exports只是一个变量，是被默认的module.exports绑定的。而CommonJS规范中没有module.exports对象。</p>
<h3 id="模块导出、引入"><a href="#模块导出、引入" class="headerlink" title="模块导出、引入"></a>模块导出、引入</h3><p>使用module.exports实现模块导出，多用于编写对外暴露统一对象API的代码；使用exports多用于编写对外暴露多个API的工具类代码。</p>
<p>其实module.exports才是真正的接口，exports只不过是它的一个辅助工具，最终将结果返回给调用方的是module.exports，而不是exports。module.exports只暴露了一个函数。，当两者共存时，module.exports优先级更高。</p>
<p>使用require来进行模块引入：要点：1、require是一个函数，参数为该模块的标识；2、require函数的返回值是module.exports对象；3、require引入的核心是模块标识，而模块标识有两种，一种是npm模块，安装于node_modules目录下；一种是自定义的本地模块，则带有相对路径。</p>
<h3 id="模块循环引用"><a href="#模块循环引用" class="headerlink" title="模块循环引用"></a>模块循环引用</h3><p>当两个不同对象各有一个强引用指向对方时，循环引用便产生了，称为module cycles。</p>
<p>在这种情况下require返回的对象必须至少包含此外部模块在调用require函数之前就已经准备完毕的输出。例如：b.js需要引用a.js，这里b.js作为当前模块，a.js就是外部模块，那么a.js应该在引用b,js之前（即进入当前模块执行环境）就返回输出。</p>
<h2 id="执行原理"><a href="#执行原理" class="headerlink" title="执行原理"></a>执行原理</h2><p>代码的每个模块在被引用时都被头尾包装，代码执行后将exports对象返回给引用方。exports其实就是通过参数传递过来的，如果exports的引用被修改，那么返回的将是原来的对象，这时需要用module.exports来代替。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"hello"</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//上面的模块代码会被包裹到函数，类似于</span></span><br><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params">exports, require, module, _filename, _dirname</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"hello"</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//代码包裹的实践如下：</span></span><br><span class="line">NativeModule.wrapper = &#123;</span><br><span class="line">    <span class="string">'(function(exports, require, module, _filename, _dirname) &#123;'</span>, <span class="string">'\n&#125;);'</span></span><br><span class="line">&#125;;</span><br><span class="line">NativeModule.wrap = <span class="function"><span class="keyword">function</span>(<span class="params">script</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> NativeModule.wrapper[<span class="number">0</span>] + script + NativeModule.wrapper[<span class="number">1</span>];</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//具体的编译源码如下：</span></span><br><span class="line">NativeModule.prototype.compile = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> source = NativeModule.getSource(<span class="keyword">this</span>.id);</span><br><span class="line">    source = NativeModule.wrap(source);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">this</span>.loading = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">var</span> fn = runInThisContext(source, &#123;</span><br><span class="line">           filename : <span class="keyword">this</span>.filename,</span><br><span class="line">           lineOffset : <span class="number">0</span>,</span><br><span class="line">           displayErrors : <span class="literal">true</span></span><br><span class="line">        &#125;);</span><br><span class="line">        fn(<span class="keyword">this</span>.exports, NativeModule.require, <span class="keyword">this</span>, <span class="keyword">this</span>.filename);</span><br><span class="line">        <span class="keyword">this</span>.loaded = <span class="literal">true</span>;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.loading = <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//具体的执行代码其实是：runInThisContext函数。</span></span><br></pre></td></tr></table></figure>

<h3 id="模块编译"><a href="#模块编译" class="headerlink" title="模块编译"></a>模块编译</h3><p>Node.js模块化编译的操作：</p>
<p>1、保证顶层变量（通过let、const、var定义），只在模块内起作用；</p>
<p>2、帮助提供一些全局查找的变量，实际上是指定给模块的变量，具体如：module.exports对象可用于从模块上对外暴露值；注入filename、dirname，即模块的文件名和路径，这样我们可以在任意文件中使用。</p>
<p> 一般在执行Node.js时，命令通常是node xxx.js。在lib/internal/bootstrap_node.js里可以找到模块执行的核心代码逻辑。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//保证process.argv[1]是完整路径</span></span><br><span class="line"><span class="keyword">const</span> path = NativeModule.require(<span class="string">'path'</span>);</span><br><span class="line">process.argv[<span class="number">1</span>] = path.resolve(process.argv[<span class="number">1</span>]);</span><br><span class="line"></span><br><span class="line"><span class="comment">//通过require引入lib/modules.js，然后赋值给Module。</span></span><br><span class="line"><span class="keyword">const</span> Module = NativeModule.require(<span class="string">'module'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//检查用户输入的-c或-check参数</span></span><br><span class="line"><span class="keyword">if</span> (process._syntax_check_only != <span class="literal">null</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> fs = NativeModule.require(<span class="string">'fs'</span>);</span><br><span class="line">    <span class="comment">//读取源码</span></span><br><span class="line">    <span class="keyword">const</span> filename = Module._resolveFilename(process.argv[<span class="number">1</span>]);</span><br><span class="line">    <span class="keyword">var</span> source = fs.readFileSync(filename, <span class="string">'utf-8'</span>);</span><br><span class="line">    checkScriptSyntax(source, filename);</span><br><span class="line">    process.exit(<span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//预加载模块preloadModules()</span></span><br><span class="line">preloadModules();</span><br><span class="line"><span class="comment">//执行模块Module.runMain()</span></span><br><span class="line">Module.runMain();</span><br></pre></td></tr></table></figure>

<p>以上代码的核心是Module.runMain()，其具体的实现代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">Module.runMain = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//加载主模块</span></span><br><span class="line">    Module._load(process.argv[<span class="number">1</span>], <span class="literal">null</span>, <span class="literal">true</span>);</span><br><span class="line">    <span class="comment">//先执行nextTickQueue中的回调函数</span></span><br><span class="line">    process._tickCallback();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//核心的Module._load方法的代码如下：</span></span><br><span class="line">Main._load = <span class="function"><span class="keyword">function</span> (<span class="params">request, parent, isMain</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (parent) &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">    tryModuleLoad(<span class="built_in">module</span>, filename);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">module</span>.exports;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">        其实以上代码的要点在于对缓存和模块类型的处理：</span></span><br><span class="line"><span class="comment">        1、如果模块已经存在于缓存中，则返回cachedModule.exports对象</span></span><br><span class="line"><span class="comment">        2、如果模块是native模块，则调用NativeModule.require(),参数为文件名，最后返回结果。</span></span><br><span class="line"><span class="comment">        3、其他情况下会为该文件创建一个新得模块，并将其保存到缓存中。随后，加载文件内容，然后返回给module.exports对象。</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">	对于我们自己编写的代码，一般会是最后这种情况，truModuleLoad的源码如下：</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">tryModuleLoad</span>(<span class="params">module, filename</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> threw = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="built_in">module</span>.load(filename);</span><br><span class="line">        threw = <span class="literal">false</span>;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (threw) &#123;</span><br><span class="line">            <span class="keyword">delete</span> Module_cache[filename];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//上面示例的核心是module.load部分，代码如下：</span></span><br><span class="line">Module.prototype.load = <span class="function"><span class="keyword">function</span> (<span class="params">filename</span>) </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">/*这里的文件后缀有三种</span></span><br><span class="line"><span class="comment">1、.js是通过module._compile来进行编译处理的，通过fs模块同步读取文件后编译执行；</span></span><br><span class="line"><span class="comment">2、.json通过JSON.parse将结果直接返回module.exports，通过fs模块同步读取文件后编译执行</span></span><br><span class="line"><span class="comment">3、.node是用c++编写的扩展文件，通过process.dlopen方法加载最后编译生成得文件，并返回结果。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h2 id="模块引用"><a href="#模块引用" class="headerlink" title="模块引用"></a>模块引用</h2><p>Node中的模块有两种类型：核心模块和文件模块，核心模块直接用名称获取。</p>
<p>require方法接收以下几种类型的参数传递：1、http、fs、path等内置模块；2、./mod等相对路径文件模块；3、/pathtomodule等绝对路径文件模块；4、mod:非原生模块的文件模块。</p>
<p>require实现的源码位于lib/internal/module.js，具体如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">makeRequireFunction</span>(<span class="params">mod</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> Module = mod.constructor;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">require</span>(<span class="params">path</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            exports.requireDepth += <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">return</span> mod.require(path);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            exports.requireDepth -= <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">resolve</span>(<span class="params">request</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Module._resolveFilename(request, mod);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">require</span>.resolve = resolve;</span><br><span class="line">    <span class="built_in">require</span>.main = process.mainModule;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//支持外部扩展类型</span></span><br><span class="line">    <span class="built_in">require</span>.extensions = Module._extensions;</span><br><span class="line">    <span class="built_in">require</span>.cache = Module._cache;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">require</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>makeRequireFunction是在lib/module.js里的compile方法中调用的，require其实是mod.require的别名，而mod其实是NativeModule的实例，所以，require是NativeModule.require的别名。</p>
<h2 id="全局对象"><a href="#全局对象" class="headerlink" title="全局对象"></a>全局对象</h2><p>模块有两种写法，一种是基于CommonJS规范编写的，第二种写法则是全局对象写法。</p>
<h3 id="内置对象"><a href="#内置对象" class="headerlink" title="内置对象"></a>内置对象</h3><p>内置对象是指在所有Node.js模块中，无须安装就可以使用的模块。可以分为以下几类：</p>
<p>1、为模块包装而提供的全局对象：例如，exports、require、module、filename、dirname。</p>
<p>2、内置的process对象，process作为核心模块，它可以对Node.js的各种信息进行绑定。</p>
<p>3、控制台Console模块。</p>
<p>4、EventLoop相关API的实现。</p>
<h3 id="Buffer"><a href="#Buffer" class="headerlink" title="Buffer"></a>Buffer</h3><p>Java中Buffer用于和NIO通道进行交互，其核心是利用缓存机制将内存块包装成NIO Buffer对象进行网络传输，并提供访问该内存块的一组方法。Node也面临一样的问题，虽然很好处理Unicode编码的字符串，但需要处理二进制数据。</p>
<p>Buffer代表一个缓冲区，用于存储二进制数据，俗称字节流，是I/O传输时常用的处理方式。相比于字符串，Buffer可以免去编码和解码的过程，节省CPU成本。Buffer也是Stream的基础。</p>
<h3 id="global"><a href="#global" class="headerlink" title="global"></a>global</h3><p>Global对象跟JS中的普通对象是一样的，主要用于扩展变量和方法。</p>
<h1 id="ES模块"><a href="#ES模块" class="headerlink" title="ES模块"></a>ES模块</h1><p>ES模块的目标是创建一个同时兼容CommonJS和AMD的格式，通过编译时加载，在编译时就能确定模块间的依赖关系，比CommonJS模块的加载效率更高。而在异步加载和配置模块加载方面，则借鉴AMD规范，提升执行效率。</p>
<p>ES6模块加载与CommonJS的差异主要以下两点：</p>
<p>1、CommonJS模块输出的是一个值的复制，ES6模块输出的是值得引用；</p>
<p>2、CommonJS模块是运行时加载，ES6模块时编译时输出接口。</p>
<h2 id="导入导出"><a href="#导入导出" class="headerlink" title="导入导出"></a>导入导出</h2><p>模块带入有两种方式，分为直接导入和按需导入。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> fs <span class="keyword">from</span> <span class="string">'fs'</span>;</span><br><span class="line"><span class="comment">//上面为直接导入，等价于CommonJS中的下面代码</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">CommonJS的加载实质上是整体加载，然后在运行是读取其方法，为运行时加载，导致完全无法在编译时进行静态优化。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; readFile &#125; <span class="keyword">from</span> <span class="string">'fs'</span>;</span><br><span class="line"><span class="comment">/*以上代码的是指是从fs模块中架子readFile方法，该加载为编译时加载或静态加载</span></span><br><span class="line"><span class="comment">即ES6可以在编译时完成模块加载，效率更高。</span></span><br><span class="line"><span class="comment">但这也导致ES6模块本身无法被引用，因为它不是对象。</span></span><br><span class="line"><span class="comment">由于ES6模块是编译时加载，使得静态分析成为可能。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>导出时，exports命令规定的是对外的接口，必须与模块内部的变量建立一一对应的关系。另外，exports语句输出的接口与其对应的值是动态绑定关系，即通过该接口可以取到模块内部实时的值。这一点与CommonJS规范完全不同，CommonJS模块输出的是值得缓存，不存在动态更新。</p>
<p>同样，由于import命令是编译阶段执行得，在代码运行之前，由于import是静态执行，所以不能使用表达式与变量，获取其他只有运行时才能得到结果得语句。</p>
<h2 id="import"><a href="#import" class="headerlink" title="import()"></a>import()</h2><p>import命令会被JS静态分析，先于模块内得其他模块执行。这样得设计固然有利于编译器提高效率，但也导致无法在运行时加载模块，在语法上使得条件加载不可能实现。</p>
<p>这里，ES6引入了import函数来完成动态加载，import(specifier)，其参数specifier指定要加载得模块的位置。</p>
<p>import()返回以恶搞Promise对象，该函数可以用在任何地方，非模块的脚本也可以使用。import()类似于Node的require方法，区别主要是：前者是异步加载，后者是同步加载。</p>
<p>应用场景：1、按需加载；2、条件加载；3、动态模块路径生成。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/10/14/node/node.js%E6%A8%A1%E5%9D%97/" title="nodejs模块">http://example.com/2021/10/14/node/node.js模块/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/node%E7%8B%BC%E4%B9%A6/" rel="tag"># node狼书</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/10/10/react/react%E5%B7%A5%E7%A8%8B%E5%B8%88%E4%BF%AE%E7%82%BC%E6%8C%87%E5%8D%97/" rel="prev" title="react工程师修炼指南（一）">
      <i class="fa fa-chevron-left"></i> react工程师修炼指南（一）
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/10/14/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/elementUI%E4%BD%BF%E7%94%A8%E9%81%BF%E5%9D%91/" rel="next" title="elementUI使用避坑">
      elementUI使用避坑 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#简单实践"><span class="nav-number">2.</span> <span class="nav-text">简单实践</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#模块规范"><span class="nav-number">3.</span> <span class="nav-text">模块规范</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#CommonJS规范"><span class="nav-number">3.1.</span> <span class="nav-text">CommonJS规范</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#模块导出、引入"><span class="nav-number">3.1.1.</span> <span class="nav-text">模块导出、引入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模块循环引用"><span class="nav-number">3.1.2.</span> <span class="nav-text">模块循环引用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#执行原理"><span class="nav-number">3.2.</span> <span class="nav-text">执行原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#模块编译"><span class="nav-number">3.2.1.</span> <span class="nav-text">模块编译</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模块引用"><span class="nav-number">3.3.</span> <span class="nav-text">模块引用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#全局对象"><span class="nav-number">3.4.</span> <span class="nav-text">全局对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#内置对象"><span class="nav-number">3.4.1.</span> <span class="nav-text">内置对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Buffer"><span class="nav-number">3.4.2.</span> <span class="nav-text">Buffer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#global"><span class="nav-number">3.4.3.</span> <span class="nav-text">global</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ES模块"><span class="nav-number">4.</span> <span class="nav-text">ES模块</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#导入导出"><span class="nav-number">4.1.</span> <span class="nav-text">导入导出</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#import"><span class="nav-number">4.2.</span> <span class="nav-text">import()</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

